import tkinter as tk
import common
import requests
import json  # 导入 json 模块

class Chat108Panel():
    __static_obj = None
    
    def __init__(self, right_panel) -> None:
        self.chat108_panel = tk.Frame(right_panel, borderwidth=1, relief=tk.SOLID, bg="blue")
        
        self.chat108_label = tk.Label(self.chat108_panel, text="chat108", font=("Arial", 14, "bold"))
        self.chat108_label.pack(side=tk.TOP, padx=10, pady=10)
        
        self.send_frame = tk.Frame(self.chat108_panel)
        self.send_frame.place(x=0, y=60, width=right_panel.winfo_width(), height=100)
        self.send_txt = tk.Text(self.send_frame)
        self.send_txt.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, pady=1)
        self.send_button = tk.Button(self.send_frame, text="发送", command=self.send_to_voice_model)
        self.send_button.pack(side=tk.LEFT, padx=10)
        
        self.recv_frame = tk.Frame(self.chat108_panel)
        self.recv_frame.place(x=0, y=130, width=right_panel.winfo_width(), height=500)
        self.recv_txt = tk.Text(self.recv_frame, state=tk.DISABLED)
        self.recv_txt.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, pady=10)
        
        self.chat108_panel.pack_forget()
        common.right_panel_register("chat108", self.chat108_panel)
        print("chat108 panel init")
    
    @classmethod
    def instance(cls, *args, **kwargs):
        if not cls.__static_obj:
            cls.__static_obj = cls(*args, **kwargs)
        return cls.__static_obj
    
    def show_chat108_panel(self):
        common.right_panel_show("chat108")
    
    def send_chat108_data(self):
        url = self.send_txt.get("1.0", tk.END)
        if url:
            self.normal_recv_txt()
            self.recv_txt.insert(tk.END, f"请求 URL: {url}\n")
            print(url)
            try:
                response = requests.get(url, allow_redirects=False)
                self.recv_txt.insert(tk.END, f"响应:\n")
                for key, value in response.headers.items():
                    self.recv_txt.insert(tk.END, f"{key}: {value}\r\n")
                self.recv_txt.insert(tk.END, f"\r\n{response.text}")
            except requests.exceptions.RequestException as e:
                self.disable_recv_txt(f"请求失败: {e}\n")
            finally:
                self.disable_recv_txt()
                pass
        pass

    def send_to_voice_model(self):
        input_text = self.send_txt.get("1.0", tk.END).strip()
        if input_text:
            self.normal_recv_txt()
            self.recv_txt.insert(tk.END, f"发送的输入: {input_text}\n")
            try:
                url = "http://172.16.30.108:11434/v1/chat/completions"
                payload = {
                    "model": "deepseek-r1:32b",
                    "messages": [
                        {"role": "system", "content": "You are a helpful assistant."},
                        {"role": "user", "content": input_text}
                    ],
                    "stream": True
                }
                headers = {
                    "authorization": "Bearer Fons1234view",
                    "Content-Type": "application/json"
                }
                response = requests.post(url, json=payload, headers=headers, stream=True)
                self.recv_txt.insert(tk.END, f"响应:\n")
                
                # 解析返回的JSON数据
                combined_content = ""
                for line in response.iter_lines():
                    if line:
                        line = line.decode('utf-8')
                        if line.startswith("data: "):
                            if line == "data: [DONE]":
                                break
                            json_data = json.loads(line[6:])
                            if 'choices' in json_data and len(json_data['choices']) > 0:
                                delta = json_data['choices'][0].get('delta', {})
                                if 'content' in delta:
                                    combined_content += delta['content']
                
                self.recv_txt.insert(tk.END, f"回答内容: {combined_content}\n")
            except requests.exceptions.RequestException as e:
                self.disable_recv_txt()
            finally:
                self.disable_recv_txt()

    def normal_recv_txt(self):
        self.recv_txt.config(state=tk.NORMAL)
        self.recv_txt.delete("1.0", tk.END)
    
    def disable_recv_txt(self):
        self.recv_txt.config(state=tk.DISABLED)
        self.recv_txt.see(tk.END)
